/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: BehaviourClient.cpp,v 1.14 2009-10-26 12:47:02 morsko Exp $
 *
 * \file
 * \brief Implementation for Behaviour interface client library.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 */

#include "BehaviourClient.hpp"
#include "BehaviourData.hpp"

//*****************************************************************************
using namespace MaCI::Behaviour;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
CBehaviourClient::CBehaviourClient(gimi::GIMI *aGIMIPtr, 
                                   const int aInterfaceMinor)
  : CSync(2,1),
    CThread(1),
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_BEHAVIOUR, aInterfaceMinor),
    iBehaviourState(false),
    iBehaviourData(),
    iBehaviourInfo(),
    iBehaviourDataSequence(-1),
    iBehaviourClientCallback(NULL)
{
  dPrint(4,"CBehaviourClient %p constructed", this);
}
//*****************************************************************************

CBehaviourClient::~CBehaviourClient()
{
  DoClose();
  dPrint(4,"CBehaviourClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CBehaviourClient::DoOpen(void)
{
  MaCI::EMaCIError result = KMaCIOK;

  //Check for gimi pointer
  if(iGIMIPtr && IsActive() == false){

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();
    
    if (result == KMaCIOK) {
      // All OK, so start the Thread
   
      SetActive(true);
      CThread::RunThread();

      //Finally ask the state of server
      CBehaviourData bd;
      bd.CreateInternalBinBag();
      bd.SetCommand(TCommand(KCommandGetBehaviourStateEvent));
      SendInterfaceMessage(bd.GetBinBagContainerPtr()->GetBuffer(),
                           bd.GetBinBagContainerPtr()->GetBufferSize());

    }
  }else{
    dPrint(1, "No GIMIPtr - No Provided service!");
    result = KMaCIError;

  }

  return result;

}
//*****************************************************************************

MaCI::EMaCIError CBehaviourClient::DoClose(void)
{
  
  EMaCIError result = KMaCIError;

  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    CThread::SetRequestTermination();
    /* CThread::CancelThread(); //Removed by script */

    result = UnsubscribeToInterface(TimeoutValue(2000));

    Notify(KNotifyEventBehaviourControl);

    Notify(KNotifyInfoReply);

    CThread::WaitThread();

    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed BehaviourClient");    
    }else{
      dPrint(4,"Unsubscribing failed!");
    }
    
    
  } else {
    dPrint(4, "BehaviourClient not active, so not Closing.");
    result = KMaCINotActive;

  }
   
  return result;

}
//*****************************************************************************

bool CBehaviourClient::SetStart()
{
  bool result = false;
  if(IsActive()){
    CBehaviourData bd;
    bd.CreateInternalBinBag();
    bd.SetCommand(TCommand(KCommandStart));
    const EMaCIError e = SendInterfaceMessage(bd.GetBinBagContainerPtr()->GetBuffer(),
                                              bd.GetBinBagContainerPtr()->GetBufferSize());
    result = (e == KMaCIOK);

  }else{
    dPrint(3,"Client inactive. Can't send 'setStart'-command!");
  }

  return result;
}
//*****************************************************************************

bool CBehaviourClient::SetStop()
{
  bool result = false;
  if(IsActive()){
    CBehaviourData bd;
    bd.CreateInternalBinBag();
    bd.SetCommand(TCommand(KCommandStop));
    const EMaCIError e = SendInterfaceMessage(bd.GetBinBagContainerPtr()->GetBuffer(),
                                              bd.GetBinBagContainerPtr()->GetBufferSize());
    result = (e == KMaCIOK);

  }else{
    dPrint(3,"Client inactive. Can't send 'setStop'-command!");
  }

  return result;

}
//*****************************************************************************

bool CBehaviourClient::GetBehaviourControlEvent(CBehaviourData &aData,
                                                int *aSequence,
                                                const int aTimeout_ms)
{
  bool result = false;
 
  // Fallback in case the class is not active.
  if (!IsActive()) return false;

  Lock();
  
  if (aSequence == NULL) {
    // No sequence number defined. Just do direct copy of local data - no sync
    aData = iBehaviourData;
    result = true;
    
  } else {
    
    if (iBehaviourDataSequence <= *aSequence) {
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();

      // The available scan is older than requested - must wait for time_left
      do {
        Wait(time_left, KNotifyEventBehaviourControl);
	time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
	
      } while(IsActive() && iBehaviourDataSequence < *aSequence && time_left > 0);
      
      // Now, check whether the waiting resulted in the correct sequence
      if (iBehaviourDataSequence > *aSequence) {
	// Yes :)
	aData = iBehaviourData;
	*aSequence = iBehaviourDataSequence;
	result = true;
        //dPrint(1,"Got data. *aSeq = %d, iBehaviourDataSequence = %d", *aSequence, iBehaviourDataSequence);
	
      } else {
	// No :(
	dPrint(8, "Failed to get BehaviourData event! (Timeout %dms)",
	       aTimeout_ms);
      }
      
    } else {
      // The available data is newer or matching.
      aData = iBehaviourData;
      *aSequence = iBehaviourDataSequence;
      //dPrint(1,"Got data. *aSeq = %d, iBehaviourDataSequence = %d", *aSequence, iBehaviourDataSequence);
      result = true;
    }
  }
  
  Unlock();
  
  return result;
}
//*****************************************************************************

bool CBehaviourClient::GetBehaviourState(void)
{
  return iBehaviourState;
}
//*****************************************************************************

bool CBehaviourClient::GetBehaviourInfo(TBehaviourInformation &info,
                                        const int aTimeout_ms)
{
  bool result = false;
  if(IsActive()){
    CBehaviourData bd;
    bd.CreateInternalBinBag();
    bd.SetCommand(TCommand(KCommandGetInfo));
    const EMaCIError e = SendInterfaceMessage(bd.GetBinBagContainerPtr()->GetBuffer(),
                                              bd.GetBinBagContainerPtr()->GetBufferSize());
    result = (e == KMaCIOK);
    if(result){
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();
      Lock();
      do {
        Wait(time_left, KNotifyInfoReply);
	time_left = TimeoutValue(aTimeout_ms)*2 - ownTime_get_ms_since(time_begin);

        //Message has arrived!
	if(time_left > 0){
          info = iBehaviourInfo;
          break;
        }
      } while(IsActive() &&  time_left > 0);
      Unlock();

    }

  }else{
    dPrint(3,"Client inactive. Can't send 'GetBehaviourInfo'-command!");
  }

  return result;

}
//*****************************************************************************

int CBehaviourClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(4, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000*60*60*24);
    if (e == KMaCIOK) {
      dPrint(8,"Got message, process it");
      ProcessMessage(gmsg);


    } else if (e != KMaCITimeout) {
      // Other error, try to recover by sleeping one second.
      dPrint(4,"MaCIError from ReceiveInterfaceMessage? ");
      if(IsActive()){
        ownSleep_ms(1000);
      }
     
      
    }

  }
  
  dPrint(4, "GIMIMessage handler stopped");

  return result;

}
//*****************************************************************************
int CBehaviourClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CBehaviourData behaviourData;
  bool r;
  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    
    behaviourData.Reset();
    r =  behaviourData.DecodeFrom(&bb);
    if (r) {
      

      // Store data to 'most-current' container.
      const MaCI::Behaviour::TCommand *cmd = behaviourData.GetCommand();
      if(cmd){
        switch(cmd->cmd){

        case  KCommandBehaviourControlEvent:{
          // Now Lock()
          Lock();
          iBehaviourData = behaviourData;
          ++iBehaviourDataSequence;
          
          Unlock();

          Notify(KNotifyEventBehaviourControl);
          // Call the handler if set.
          if (iBehaviourClientCallback) {
            dPrint(8,"Got Callback for BehaviourCtrlEvent - executing!");
            iBehaviourClientCallback->OnBehaviourCtrlEvent(behaviourData,
                                                       iBehaviourDataSequence,
                                                       *this);
            dPrint(8,"Callback for BehaviourCtrlEvent - execution complete!");
          } 
          break;
        }

        case KCommandBehaviourStateEvent:{
          Lock();
          if(behaviourData.GetBehaviourState()){
            if(behaviourData.GetBehaviourState()->state == 0){
              iBehaviourState = false;
            }else{
              iBehaviourState = true;
            }
          
          Unlock();
          if (iBehaviourClientCallback) {
            dPrint(8,"Got Callback for BehaviourCtrlEvent - executing!");
            iBehaviourClientCallback->OnBehaviourStateEvent(behaviourData,
                                                            iBehaviourDataSequence,
                                                            *this);
            dPrint(8,"Callback for BehaviourCtrlEvent - execution complete!");
          } 
          }
          break;
        }

        case KCommandGetInfoReply:{
          Lock();

          TBehaviourInformation info = *(behaviourData.GetBehaviourInfo());

          iBehaviourInfo = info;

          Unlock();
          Notify(KNotifyInfoReply);
          
        }
        }
      }
     
     
    }
  }
  return result;
}
//*****************************************************************************

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
